package com.lp.multi.juc;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author: lp
 * @create: 2021-06-26 10:54
 * @description: lock版本生产者消费者
 */
public class ThreadTeamWorkLockTest {
    public static void main(String[] args) {
        Goods goods = new Goods();
        new Thread(()->{
            try {
                TimeUnit.SECONDS.sleep(1);
                goods.increament();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        },"a1").start();
        new Thread(()->{
            try {
                TimeUnit.SECONDS.sleep(1);
                goods.increament();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        },"a2").start();
        new Thread(()->{
            try {
                TimeUnit.SECONDS.sleep(1);
                goods.reduce();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        },"b1").start();
        new Thread(()->{
            try {
                TimeUnit.SECONDS.sleep(1);
                goods.reduce();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        },"b2").start();

    }
}


class Goods{
    private Integer number =0;
    private Lock lock = new ReentrantLock();
    //监视器
    private Condition condition = lock.newCondition();

    public void increament() throws InterruptedException {
        lock.lock();
        try{
            while (number !=0){
                    condition.await();

            }
            number ++;
            System.out.println(Thread.currentThread().getName()+":" + (number));
            //需要释放锁前,唤醒其他锁
            condition.signalAll();
        }finally {
            lock.unlock();
        }


    }


    public void reduce() throws InterruptedException {
        lock.lock();
        try{
            while (number !=1){
                    condition.await();
            }
            number --;
            System.out.println(Thread.currentThread().getName()+":" + (number));
            condition.signalAll();
        }finally {
            lock.unlock();
        }

    }

}